package l1j.server.server;

/**
 * 
 * 倍率动态调整
 * 
 */
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Properties;
import william.L1GameReStart;

import l1j.server.Config;
import l1j.server.server.model.L1World;

public class RateChangeController implements Runnable {

	private static RateChangeController _instance;
	
	private static final String ALT_SETTINGS_FILE = "./config/altsettings.properties";

	private static String crType;
	
	private static String crDate;

	private static String StartTime;
	
	private static String ChangeInTime;
	
	private static int cRateXp;
	
	private static int cRateDropAdena;
	
	private static int RateDropItems;

	private static boolean _runFlag = true;
	
	private static boolean _inChangeRate  =false;
	
	public static boolean _changed = false;
	
	private static boolean _onlyEnd = false; //当前时间小于起始时间
	
	public static RateChangeController getInstance() {
		if (_instance == null) {
			_instance = new RateChangeController();
		}
		return _instance;
	}
	
	private RateChangeController() {
		//加载参数
		try {
			Properties altSettings = new Properties();
			InputStream is = new FileInputStream(new File(ALT_SETTINGS_FILE));
			altSettings.load(is);
			is.close();
			
			crType = altSettings.getProperty("crType", "");
			crDate = altSettings.getProperty("crDate", "");
			StartTime = altSettings.getProperty("StartTime", "");
			ChangeInTime = altSettings.getProperty("ChangeInTime", "");
			cRateXp = Integer.parseInt(altSettings.getProperty("cRateXp", "1"));
			cRateDropAdena = Integer.parseInt(altSettings.getProperty("cRateDropAdena", "1"));
			RateDropItems = Integer.parseInt(altSettings.getProperty("RateDropItems", "1"));			
			if (!checkConfig()) {
				_runFlag = false;
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new Error("Failed to Load " + ALT_SETTINGS_FILE + " File.");
		}
	}

	private boolean checkConfig() {
		if (crType.length()==0 || crDate.length()==0 || StartTime.length()==0
				|| ChangeInTime.length()==0) {
			return false;
		}
		return true;
	}
	
	private static double _s = 0.0;	//最佳时间的起始时间
	
	private static double _e = 0.0;	//最佳时间的结束时间
	
	private boolean getNearWeekTime(GregorianCalendar gc) {
		GregorianCalendar cgc = new GregorianCalendar(); //取得当前日历
		int _day = cgc.get(Calendar.DAY_OF_WEEK); // 取得今天是本周的第几天
		_day = _day==1?7:_day-1;	//偏移成中国式的week day
		try{
			int len = 0;
			len = crDate.trim().split("/").length;
			GregorianCalendar tgc = new GregorianCalendar();
			int offset = 0;	
			double _min = 24*3600*1000;
			_s = 0.0;
			_e = 0.0;
			for (int i=0; i<len; i++) {
				int j = Integer.parseInt(crDate.trim().split("/")[i]); //目标日期
				if (_day > j) { //目标日期已过的不予处理
					continue;
				}
				offset = j>=6?j-6:j+1;
				tgc.set(Calendar.DAY_OF_WEEK, offset);
				tgc.set(Calendar.HOUR_OF_DAY, 0);
				tgc.set(Calendar.MINUTE, 0);
				tgc.set(Calendar.SECOND, 0);
				int starttime = 0;
				if (StartTime.trim().split(":").length==1) { //参数只有小时
					starttime += Integer.parseInt(StartTime.trim().split(":")[0])*3600;	//偏移成起始时间
				} else if (StartTime.trim().split(":").length==2) { //参数为 小时:分钟
					starttime += Integer.parseInt(StartTime.trim().split(":")[0])*3600
							+ Integer.parseInt(StartTime.trim().split(":")[1])*60;
				} else if (StartTime.trim().split(":").length==3) { //参数为 小时:分钟:秒
					starttime += Integer.parseInt(StartTime.trim().split(":")[0])*3600
							+ Integer.parseInt(StartTime.trim().split(":")[1])*60
							+ Integer.parseInt(StartTime.trim().split(":")[2]);
				}
				tgc.add(Calendar.SECOND, starttime);
				if (_min>Math.abs(System.currentTimeMillis()-tgc.getTimeInMillis())) {
					_min = Math.abs(System.currentTimeMillis()-tgc.getTimeInMillis());
					_s = tgc.getTimeInMillis();
				}
			}
			//结算结束时间
			if ((ChangeInTime.trim().endsWith("h"))) {
				_e = _s + Double.parseDouble(ChangeInTime.trim().split("h")[0])*3600*1000;
			} else if ((ChangeInTime.trim().endsWith("m"))) {
				_e = _s + Double.parseDouble(ChangeInTime.trim().split("m")[0])*60*1000;
			} else if ((ChangeInTime.trim().endsWith("s"))) {
				_e = _s + Double.parseDouble(ChangeInTime.trim().split("s")[0])*1000;
			}
			if (_s > gc.getTimeInMillis()) {
				return false;
			}
			if (System.currentTimeMillis()>_e) {
				return false;
			}
			if (System.currentTimeMillis()>_s && System.currentTimeMillis()<_e) {
				_onlyEnd = true;
				return true;
			}
			if (System.currentTimeMillis()<_s && System.currentTimeMillis()<_e) {
				return true;
			}
		} catch (NumberFormatException e) {
			return false;
		}
		return false;
	}
	
	private boolean checkTime() {
		if (_inChangeRate) {
			return true;
		}
		int rTime = L1GameReStart.getRestartT(); //取得当前服务器重启剩余时间
		GregorianCalendar ngc = new GregorianCalendar(); //构造当前时间
		ngc.add(Calendar.SECOND, rTime);	//偏移到重启时间
		if (getNearWeekTime(ngc)) {
			if (_s!=0 &&_e!=0 && _dptime==-10) {
				_inChangeRate = true;
				return true;
			}
		}
		return false;
	}
	
	private static int _dptime = -10;
	
	@Override
	public void run() {
		while (_runFlag) {
			if (checkTime()) {
				if (_onlyEnd) {
					if (_inChangeRate && !_changed && _dptime==-10) {
						Config.RATE_XP = Config.RATE_XP*cRateXp;
						Config.RATE_DROP_ADENA = Config.RATE_DROP_ADENA*cRateDropAdena;
						Config.RATE_DROP_ITEMS = Config.RATE_DROP_ITEMS*RateDropItems;
						if (_dptime==-10) {
							_dptime = (int)(_e - System.currentTimeMillis())/1000;
						}
						L1World.getInstance().broadcastServerMessage("[系统公告] 倍率调整活动开始");
						_changed = true;
					}
					if (_inChangeRate && _changed && _dptime!=-10) {
						_dptime--;
						if (_dptime==0) {
							_inChangeRate = false;
							_onlyEnd = false;
							_dptime = -10;
						}
					}
					if (!_inChangeRate && _changed && _dptime==-10) {
						Config.RATE_XP = Config.RATE_XP/cRateXp;
						Config.RATE_DROP_ADENA = Config.RATE_DROP_ADENA/cRateDropAdena;
						Config.RATE_DROP_ITEMS = Config.RATE_DROP_ITEMS/RateDropItems;
						_changed = false;
						L1World.getInstance().broadcastServerMessage("[系统公告] 倍率调整活动结束");
					}
				} else {
					if (_dptime==-10) {
						_dptime = (int)(_s-System.currentTimeMillis())/1000;
					} else {
						if (_dptime!=-10) {
							_dptime--;
						}
					}
					if (_dptime==0) {
						_onlyEnd = true;
						_dptime = -10;
					}
				}
			}
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}